﻿using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace G.XNA
{
    /// <summary>
    /// 通过几何学中的斜线方程x=ay+b来根据y的值获取x的集合，一个y对应零或一个x点
    /// </summary>
    public struct LineSegment : IGeometrySegment
    {
        readonly float a, b;         // as in x = ay + b

        public LineSegment(Vector2 point1, Vector2 point2)
            : this()
        {
            Point1 = point1;
            Point2 = point2;

            a = (Point2.X - Point1.X) / (Point2.Y - Point1.Y);//计算斜率
            b = Point1.X - a * Point1.Y;//计算y轴的截距
        }

        public Vector2 Point1 { private set; get; }
        public Vector2 Point2 { private set; get; }
        /// <summary>
        /// 检查条件中y值好汉Point1值但是不包含Point2，因为在多条线和弧线连接时，避免了在集合中有多个重复的x值
        /// 即y >= Point1.Y && y< Point2.Y)
        /// 当Point1=Point2时，得不到值
        /// </summary>
        /// <param name="y"></param>
        /// <param name="xCollection"></param>
        public void GetAllX(float y, IList<float> xCollection)
        {
            if ((Point2.Y > Point1.Y && y >= Point1.Y && y < Point2.Y) ||
                (Point2.Y < Point1.Y && y <= Point1.Y && y > Point2.Y))
            {
                xCollection.Add(a * y + b);
            }
        }
    }
}
